from contextlib import contextmanager
from psycopg_pool import ConnectionPool


def dict_row_factory(cursor):
    fields = [c.name for c in cursor.description]
    print("fields: ", fields)

    def make_row(values):
        print("fields-values: ", fields, values)
        return dict(zip(fields, values))

    return make_row


dsn = "host=localhost dbname=examdb user=examdb"
dbconn_pool = ConnectionPool(dsn, min_size=4)


@contextmanager
def dblock():
    with dbconn_pool.connection() as conn:
        try:
            with conn.cursor(row_factory=dict_row_factory) as cur:
                yield cur
            conn.commit()
        except:
            conn.rollback()
            raise
